package cn.com.dashihui.wx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.api.PaymentApi.TradeType;
import com.jfinal.weixin.sdk.kit.PaymentKit;

import cn.com.dashihui.wx.common.CartKit;
import cn.com.dashihui.wx.common.CartKit.Cart;
import cn.com.dashihui.wx.common.CartKit.CartGoods;
import cn.com.dashihui.wx.common.OrderCode;
import cn.com.dashihui.wx.dao.Order;
import cn.com.dashihui.wx.dao.OrderPayAPIRecord;
import cn.com.dashihui.wx.dao.User;
import cn.com.dashihui.wx.dao.WxUser;
import cn.com.dashihui.wx.interceptor.AuthLoginInterceptor;
import cn.com.dashihui.wx.interceptor.RefreshLoginInterceptor;
import cn.com.dashihui.wx.kit.CommonKit;
import cn.com.dashihui.wx.kit.DatetimeKit;
import cn.com.dashihui.wx.kit.DoubleKit;
import cn.com.dashihui.wx.kit.MapKit;
import cn.com.dashihui.wx.service.OrderService;
import cn.com.dashihui.wx.service.UserService;

@Before(AuthLoginInterceptor.class)
public class OrderController extends BaseController{
	private Logger logger = Logger.getLogger(getClass());
	//使用Duang.duang进行封装，使普通类具有事务的功能
	private OrderService service = Duang.duang(OrderService.class);
	private UserService userService = new UserService();
	
	/**
	 * 确认订单<br/>
	 * 从购物车点击“去结算”后，跳转至订单确认页面
	 */
	public void confirm(){
		String choosedGoodsid = getPara("choosedGoodsid");
		//判断session中是否有购物车
		if(!CartKit.hasCart(getSession(), getCurrentStoreid())||StrKit.isBlank(choosedGoodsid)){
			//如果没有购物车，则说明购物车已经被结算或者没有数据，此时直接跳转至订单列表页
			redirect("/order/list");
			return;
		}
		//将用户所选择的商品从购物车中选出来
		Cart cart1 = CartKit.getCart(getSession(), 0),cart1Clone = new Cart(cart1.getStoreid());
		Cart cart2 = CartKit.getCart(getSession(),getCurrentStoreid()),cart2Clone = new Cart(cart2.getStoreid());
		for(String goodsid : choosedGoodsid.split(",")){
			if(cart1.hasGoods(goodsid)){
				cart1Clone.add(cart1.getGoods(goodsid));
			}else if(cart2.hasGoods(goodsid)){
				cart2Clone.add(cart2.getGoods(goodsid));
			}else{
				//商品ID不存在，跳转至订单列表页
				redirect("/order/list");
				return;
			}
		}
		setAttr("choosedGoodsid",choosedGoodsid);//将选中的商品ID传给下一个页面
		setAttr("cart1", cart1Clone);//大实惠自营
		setAttr("cart2", cart2Clone);//便利店
		setAttr("cartTotal", DoubleKit.add(cart1Clone.getTotal(), cart2Clone.getTotal()));
		setAttr("addressDef", userService.findDefaultAddressByUser(getCurrentUserid()));
		User user = User.me().findById(getCurrentUser().get("id"));
		if(user != null){
			setAttr("userMoney",user.getDouble("money"));
		}
		render("confirm.jsp");
	}

	/**
	 * 保存订单<br/>
	 * 在保存订单时，需要验证<br/>
	 * 1.验证所购买商品是否是“上架”状态
	 * 2.对商品数量是否超过限购数量作验证，如果不符合则保存不在成功
	 * @param payType 支付方式
	 * @param takeType 取货方式
	 * @param linkName 联系人姓名
	 * @param sex 性别
	 * @param tel 电话
	 * @param address 地址
	 * @param describe 订单备注
	 * @return forwardFlag 1:跳转到支付页面，2：跳转到订单列表
	 */
	public void save(){
		//验证店铺黑名单（有些店铺不允许下单）
		String storeOfBlackList = PropKit.get("black.store");
		if(!StrKit.isBlank(storeOfBlackList)){
			String[] storeList = storeOfBlackList.split(",");
			for(String storeid : storeList){
				if(storeid.equals(String.valueOf(getCurrentStoreid()))){
					renderFailed("您所在的小区暂未开通服务，敬请期待！");
					return;
				}
			}
		}
		String choosedGoodsid = getPara("choosedGoodsid");
		//判断session中是否有购物车
		if(!CartKit.hasCart(getSession(), getCurrentStoreid())&&!CartKit.hasCart(getSession(), 0)){
			renderResult(1,"购物车为空");
			return;
		}else if(StrKit.isBlank(choosedGoodsid)){
			renderResult(2,"未选择要结账的商品");
			return;
		}
		//将用户所选择的商品从购物车中选出来
		Cart cart1Src = CartKit.getCart(getSession(), 0),cart1Clone = new Cart(cart1Src.getStoreid());
		Cart cart2Src = CartKit.getCart(getSession(),getCurrentStoreid()),cart2Clone = new Cart(cart2Src.getStoreid());
		for(String goodsid : choosedGoodsid.split(",")){
			if(cart1Src.hasGoods(goodsid)){
				cart1Clone.add(cart1Src.getGoods(goodsid));
			}else if(cart2Src.hasGoods(goodsid)){
				cart2Clone.add(cart2Src.getGoods(goodsid));
			}else{
				//商品ID不存在，跳转至订单列表页
				redirect("/order/list");
				return;
			}
		}
		String storePayType = getPara("storePayType");
		String storeTakeType = getPara("storeTakeType");
		String selfPayType = getPara("selfPayType");
		String selfTakeType = getPara("selfTakeType");
		String linkName = getPara("linkName");
		String sex = getPara("sex");
		String tel = getPara("tel");
		String address = getPara("address");
		String describe = getPara("describe");
		int isRedeem = getParaToInt("isRedeem");
		if(StrKit.isBlank(linkName)){
			renderResult(4,"参数LINKNAME不能为空");
    		return;
		}else if(StrKit.isBlank(sex)){
			renderResult(5,"参数SEX不能为空");
    		return;
		}else if(StrKit.isBlank(tel)){
			renderResult(6,"参数TEL不能为空");
    		return;
		}else if(StrKit.isBlank(address)){
			renderResult(7,"参数ADDRESS不能为空");
    		return;
		}else if(!StrKit.isBlank(describe)&&describe.length()>=200){
			renderFailed("参数DESCRIBE内容过长");
    		return;
		}
		//将购物车中商品整理出ID数组、数量数组，方便下方进行下单前验证
		List<CartGoods> selfGoodsList = cart1Clone.getList();
		List<CartGoods> storeGoodsList = cart2Clone.getList();
		//1.自营商品不为空，店铺商品为空
		if(selfGoodsList.size() > 0 && storeGoodsList.size() <= 0){
			if(StrKit.isBlank(selfPayType)){
				renderResult(2,"参数PAYTYPE不能为空");
	    		return;
			}else if(StrKit.isBlank(selfTakeType)){
				renderResult(3,"参数TAKETYPE不能为空");
	    		return;
			}			
			
			String selfGoodsidArray[] = new String[selfGoodsList.size()];
			int selfCountArray[] = new int[selfGoodsList.size()];
			double selfTotalArray[] = new double[selfGoodsList.size()];
			for(int i=0;i<selfGoodsList.size();i++){
				CartGoods selfGoods = selfGoodsList.get(i);
				selfGoodsidArray[i] = selfGoods.getId();
				selfCountArray[i] = selfGoods.getCounter();
				selfTotalArray[i] = selfGoods.getTotal();
			}
			//验证用户要购买的商品
			//1.验证是否有商品已下架
			//2.验证是否有商品购买量已经超过了今日所限量
			//3.验证总金额是否与客户端的入参总金额相同
			int validate = service.validate(getCurrentUserid(),getCurrentStoreid(),selfGoodsidArray,selfCountArray,cart1Clone.getTotal());
			if(validate==1){
				renderFailed("您所购买的商品中有已下架的商品");
				return;
			}else if(validate==2){
				renderFailed("您所购买的商品中有超出限量的商品");
				return;
			}else if(validate==3){
				renderFailed("总金额计算不正确");
				return;
			}
			//生成普通商品类订单的订单编号，以大写字母G开头
			String selfOrderNum = "WG"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(2);
			//保存订单
			Order selfOrder = new Order()
					.set("orderNum", selfOrderNum)
					.set("from", OrderCode.OrderFrom.WXSELLER)
					.set("storeid", 0)
					.set("userid", getCurrentUserid())
					.set("amount", cart1Clone.getTotal())
					.set("payType", Integer.valueOf(selfPayType).intValue())
					.set("payState", OrderCode.OrderPayState.NO_PAY)
					.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
					.set("orderState", OrderCode.OrderState.NORMAL)
					.set("takeType", Integer.valueOf(selfTakeType).intValue())
					.set("deliverType", OrderCode.OrderDeliverType.ON_LOGISTICS)
					.set("linkName", linkName)
					.set("sex", sex)
					.set("tel", tel)
					.set("address", address)
					.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
					.set("isSelf", 1);
			if(StrKit.notBlank(describe)){
				selfOrder.set("describe", describe);
			}
			int result = 0;
			try {
				result = service.doRedeem(null, selfOrder, null, selfGoodsidArray, null, selfCountArray, null, selfTotalArray, getCurrentUserid(), isRedeem);
				service.save(selfOrder, selfGoodsidArray, selfCountArray, selfTotalArray);
				service.log(selfOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户",OrderCode.OrderLogType.SAVE_ACTION,"订单已提交，请尽快支付");
				//将用户所选择的商品从购物车中移除
				for(CartGoods goods : selfGoodsList){
					cart1Src.delete(goods.getId());
				}
				renderSuccess(MapKit.one().put("orderNum",selfOrderNum).getAttrs());
				return;
			} catch (Exception e) {
				e.printStackTrace();
				renderFailed("保存订单失败");
				return;
			}
			renderSuccess(MapKit.one().put("forwardFlag", result).put("orderNum",selfOrderNum).getAttrs());
			return;
		// 2.自营商品为空，店铺商品不为空
		} else if(selfGoodsList.size() <= 0 && storeGoodsList.size() > 0){
			if(StrKit.isBlank(storePayType)){
				renderResult(2,"参数PAYTYPE不能为空");
	    		return;
			}else if(StrKit.isBlank(storeTakeType)){
				renderResult(3,"参数TAKETYPE不能为空");
	    		return;
			}
			
			String storeGoodsidArray[] = new String[storeGoodsList.size()];
			int storeCountArray[] = new int[storeGoodsList.size()];
			double storeTotalArray[] = new double[storeGoodsList.size()];
			for(int i=0;i<storeGoodsList.size();i++){
				CartGoods storeGoods = storeGoodsList.get(i);
				storeGoodsidArray[i] = storeGoods.getId();
				storeCountArray[i] = storeGoods.getCounter();
				storeTotalArray[i] = storeGoods.getTotal();
			}
			//验证用户要购买的商品
			//1.验证是否有商品已下架
			//2.验证是否有商品购买量已经超过了今日所限量
			//3.验证总金额是否与客户端的入参总金额相同
			int validateStoreGoods = service.validate(getCurrentUserid(),getCurrentStoreid(),storeGoodsidArray,storeCountArray,cart2Clone.getTotal());
			if(validateStoreGoods==1){
				renderFailed("您所购买的商品中有已下架的商品");
				return;
			}else if(validateStoreGoods==2){
				renderFailed("您所购买的商品中有超出限量的商品");
				return;
			}else if(validateStoreGoods==3){
				renderFailed("总金额计算不正确");
				return;
			}
			//生成普通商品类订单的订单编号，以大写字母G开头
			String storeOrderNum = "WG"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(2);
			//保存订单
			Order storeOrder = new Order()
					.set("orderNum", storeOrderNum)
					.set("from", OrderCode.OrderFrom.WXSELLER)
					.set("storeid", getCurrentStoreid())
					.set("userid", getCurrentUserid())
					.set("amount", cart2Clone.getTotal())
					.set("payType", Integer.valueOf(storePayType).intValue())
					.set("payState", OrderCode.OrderPayState.NO_PAY)
					.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
					.set("orderState", OrderCode.OrderState.NORMAL)
					.set("takeType", Integer.valueOf(storeTakeType).intValue())
					.set("deliverType", OrderCode.OrderDeliverType.ON_STORE)
					.set("linkName", linkName)
					.set("sex", sex)
					.set("tel", tel)
					.set("address", address)
					.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
					.set("isSelf", 0);
			if(StrKit.notBlank(describe)){
				storeOrder.set("describe", describe);
			}
			int result = 0;
			try {
				result = service.doRedeem(storeOrder, null, storeGoodsidArray, null, storeCountArray, null, storeTotalArray, null, getCurrentUserid(), isRedeem);
				service.save(storeOrder, storeGoodsidArray, storeCountArray, storeTotalArray);
				//根据订单支付方式不同，记录日志不同
				if(Integer.valueOf(storePayType)==OrderCode.OrderPayType.ON_LINE){
					service.log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，请尽快支付");
				}else{
					service.log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，等待系统确认");
				}
				//将用户所选择的商品从购物车中移除
				for(CartGoods goods : storeGoodsList){
					cart2Src.delete(goods.getId());
				}
				renderSuccess(MapKit.one().put("orderNum",storeOrderNum).getAttrs());
				return;
			} catch (Exception e) {
				e.printStackTrace();
				renderFailed("保存订单失败");
				return;
			}
			renderSuccess(MapKit.one().put("forwardFlag", result).put("orderNum",storeOrderNum).getAttrs());
			return;
		//3.自营商品、店铺商品都不为空
		} else if(selfGoodsList.size() > 0 && storeGoodsList.size() > 0){
			if(StrKit.isBlank(storePayType)||StrKit.isBlank(selfPayType)){
				renderResult(2,"参数PAYTYPE不能为空");
	    		return;
			}else if(StrKit.isBlank(storeTakeType)||StrKit.isBlank(selfTakeType)){
				renderResult(3,"参数TAKETYPE不能为空");
	    		return;
			}
			
			//生成普通大实惠自营商品类订单的订单编号，以大写字母G开头
			String selfOrderNum = "WG"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(2);
			//生成普通便利店商品类订单的订单编号，以大写字母G开头
			String storeOrderNum = "WG"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(2);
			//生成服务类订单的合单编号，以大写字母G开头
			String mergerNum = "WG"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(2);
			
			String selfGoodsidArray[] = new String[selfGoodsList.size()];
			int selfCountArray[] = new int[selfGoodsList.size()];
			double selfTotalArray[] = new double[selfGoodsList.size()];
			for(int i=0;i<selfGoodsList.size();i++){
				CartGoods selfGoods = selfGoodsList.get(i);
				selfGoodsidArray[i] = selfGoods.getId();
				selfCountArray[i] = selfGoods.getCounter();
				selfTotalArray[i] = selfGoods.getTotal();
			}
			//验证用户要购买的商品
			//1.验证是否有商品已下架
			//2.验证是否有商品购买量已经超过了今日所限量
			//3.验证总金额是否与客户端的入参总金额相同
			int validateSelfGoods = service.validate(getCurrentUserid(),getCurrentStoreid(),selfGoodsidArray,selfCountArray,cart1Clone.getTotal());
			if(validateSelfGoods==1){
				renderFailed("您所购买的商品中有已下架的商品");
				return;
			}else if(validateSelfGoods==2){
				renderFailed("您所购买的商品中有超出限量的商品");
				return;
			}else if(validateSelfGoods==3){
				renderFailed("总金额计算不正确");
				return;
			}
			//保存自营订单
			Order selfOrder = new Order()
					.set("orderNum", selfOrderNum)
					.set("from", OrderCode.OrderFrom.WXSELLER)
					.set("storeid", 0)
					.set("userid", getCurrentUserid())
					.set("amount", cart1Clone.getTotal())
					.set("payType", Integer.valueOf(selfPayType).intValue())
					.set("payState", OrderCode.OrderPayState.NO_PAY)
					.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
					.set("orderState", OrderCode.OrderState.NORMAL)
					.set("takeType", Integer.valueOf(selfTakeType).intValue())
					.set("deliverType", OrderCode.OrderDeliverType.ON_LOGISTICS)
					.set("linkName", linkName)
					.set("sex", sex)
					.set("tel", tel)
					.set("address", address)
					.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
					.set("isSelf", 1)
					.set("mergerNum", mergerNum);
			
			
			String storeGoodsidArray[] = new String[storeGoodsList.size()];
			int storeCountArray[] = new int[storeGoodsList.size()];
			double storeTotalArray[] = new double[storeGoodsList.size()];
			for(int i=0;i<storeGoodsList.size();i++){
				CartGoods storeGoods = storeGoodsList.get(i);
				storeGoodsidArray[i] = storeGoods.getId();
				storeCountArray[i] = storeGoods.getCounter();
				storeTotalArray[i] = storeGoods.getTotal();
			}
			//验证用户要购买的商品
			//1.验证是否有商品已下架
			//2.验证是否有商品购买量已经超过了今日所限量
			//3.验证总金额是否与客户端的入参总金额相同
			int validateStoreGoods = service.validate(getCurrentUserid(),getCurrentStoreid(),storeGoodsidArray,storeCountArray,cart2Clone.getTotal());
			if(validateStoreGoods==1){
				renderFailed("您所购买的商品中有已下架的商品");
				return;
			}else if(validateStoreGoods==2){
				renderFailed("您所购买的商品中有超出限量的商品");
				return;
			}else if(validateStoreGoods==3){
				renderFailed("总金额计算不正确");
				return;
			}
			//保存店铺订单
			Order storeOrder = new Order()
					.set("orderNum", storeOrderNum)
					.set("from", OrderCode.OrderFrom.WXSELLER)
					.set("storeid", getCurrentStoreid())
					.set("userid", getCurrentUserid())
					.set("amount", cart2Clone.getTotal())
					.set("payType", Integer.valueOf(storePayType).intValue())
					.set("payState", OrderCode.OrderPayState.NO_PAY)
					.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
					.set("orderState", OrderCode.OrderState.NORMAL)
					.set("takeType", Integer.valueOf(storeTakeType).intValue())
					.set("deliverType", OrderCode.OrderDeliverType.ON_STORE)
					.set("linkName", linkName)
					.set("sex", sex)
					.set("tel", tel)
					.set("address", address)
					.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
					.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
					.set("isSelf", 0)
					.set("mergerNum", mergerNum);
			if(StrKit.notBlank(describe)){
				selfOrder.set("describe", describe);
				storeOrder.set("describe", describe);
			}
			int result = 0;
			try {
				result = service.doRedeem(storeOrder, selfOrder, storeGoodsidArray, selfGoodsidArray, storeCountArray, selfCountArray, storeTotalArray, selfTotalArray, getCurrentUserid(), isRedeem);
				service.save(selfOrder, selfGoodsidArray, selfCountArray, selfTotalArray);
				service.log(selfOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户",OrderCode.OrderLogType.SAVE_ACTION,"订单已提交，请尽快支付");
				
				service.save(storeOrder, storeGoodsidArray, storeCountArray, storeTotalArray);
				//根据订单支付方式不同，记录日志不同
				if(Integer.valueOf(storePayType)==OrderCode.OrderPayType.ON_LINE){
					service.log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，请尽快支付");
				}else{
					service.log(storeOrder.getStr("orderNum"),OrderCode.OrderLogType.SAVE,"用户", OrderCode.OrderLogType.SAVE_ACTION, "订单已提交，等待系统确认");
				}
				//将用户所选择的商品从购物车中移除
				for(CartGoods goods : selfGoodsList){
					cart1Src.delete(goods.getId());
				}
				for(CartGoods goods : storeGoodsList){
					cart2Src.delete(goods.getId());
				}
				renderSuccess(MapKit.one().put("orderNum",mergerNum).getAttrs());
				return;
			} catch (Exception e) {
				e.printStackTrace();
				renderFailed("保存订单失败");
				return;
			}
		}
	}
	
	/**
	 * 订单保存成功，展示订单编号等信息，并准备微信支付
	 */
	public void prepay(){
		String orderNum = getPara(0);
		if(StrKit.isBlank(orderNum)){
			redirect("/index");
			return;
		}
		//查询对应的订单信息
		List<Order> orderList = service.getOrderListByMergerOrderNum(getCurrentUserid(),orderNum);
		if(orderList==null || orderList.size() <= 0){
			redirect("/index");
			return;
		}
		//验证订单是否有效
		if(DatetimeKit.compareDate(orderList.get(0).getDate("expireDate")) == -1){
			//如果失效，则跳转至订单详情页面
			redirect("/order/detail/"+orderNum);
			return;
		}
		//获取调用微信js接口所需要的参数
		getJSApiParams(PropKit.get("constants.url_prev")+"/order/prepay/"+orderNum);
		
		//计算订单总金额
		double amount = 0;
		for(int i = 0; i < orderList.size(); i++){
			double orderAmount = orderList.get(i).get("realPay");
			amount = DoubleKit.add(amount, orderAmount);
		}
		setAttr("orderNum", orderNum);
		setAttr("amount",amount);
		render("prepay.jsp");
	}
	
	/**
	 * 微信预支付，生成预支付相应的参数
	 * @param orderNum 订单号
	 * @param flag 用户所选择的支付方式，1:微信支付
	 */
	public void doPrePay(){
		WxUser wxUser = getCurrentWxUser();
		//判断当前登录用户是否已授权
		if(wxUser==null){
			renderResult(1);
			return;
		}
		String orderNum = getPara("orderNum");
		String flagStr = getPara("flag");
		//查询对应的订单信息
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(flagStr)){
			renderFailed("参数FLAG不能为空");
    		return;
		}else if(!flagStr.equals(String.valueOf(OrderCode.OrderPayMethod.WEIXIN))){
			renderFailed("参数FLAG不正确");
    		return;
		}
		//查询订单详情并以此验证订单号
		List<Order> orderList = service.getOrderListByMergerOrderNum(getCurrentUserid(),orderNum);
		if(orderList==null || orderList.size() <= 0){
			renderFailed("订单不存在");
    		return;
		}
		int payMethod = Integer.valueOf(flagStr);
		if(payMethod == OrderCode.OrderPayMethod.WEIXIN){
			//1：微信支付
			//验证订单是否有效
			String startDate = DatetimeKit.getFormatDate(orderList.get(0).getDate("startDate"),"yyyyMMddHHmmss");
			String expireDate = DatetimeKit.getFormatDate(orderList.get(0).getDate("expireDate"),"yyyyMMddHHmmss");
			if(DatetimeKit.compareDate(orderList.get(0).getDate("expireDate")) == -1){
				renderFailed("您的订单已过期");
	    		return;
			}
			//计算订单总金额
			double amount = 0;
			for(int i = 0; i < orderList.size(); i++){
				double orderAmount = orderList.get(i).get("realPay");
				amount = DoubleKit.add(amount, orderAmount);
			}
			//获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			//openId，采用 网页授权获取 access_token API：SnsAccessTokenApi获取
			String openId = wxUser.getStr("openid");
			//统一下单文档地址：https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
			Map<String, String> params = new HashMap<String, String>();
			params.put("appid", PropKit.get("wx.pay.appId"));
			params.put("mch_id", PropKit.get("wx.pay.mch_id"));
			params.put("body", "大实惠云超市");
			params.put("out_trade_no", orderNum);
			params.put("total_fee", amountStr);//总金额单位为分
			params.put("time_start", startDate);
			params.put("time_expire", expireDate);
			String ip = CommonKit.getClientIp(getRequest());
			if (StrKit.isBlank(ip)) {
				ip = "127.0.0.1";
			}
			params.put("spbill_create_ip", ip);
			params.put("trade_type", TradeType.JSAPI.name());
			params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
			params.put("notify_url", PropKit.get("wx.pay.notifyUrl"));
			params.put("openid", openId);
			//生成签名
			params.put("sign", PaymentKit.createSign(params, PropKit.get("wx.pay.key")));
			logger.error(params.toString());
			//统一下单
			String xmlResult = PaymentApi.pushOrder(params);
			System.out.println(xmlResult);
			//保存接口请求和响应内容日志
			new OrderPayAPIRecord().set("orderNum", orderNum)
				.set("sendContent", params.toString())
				.set("returnContent", xmlResult)
				.set("payMethod", payMethod)
				.set("flag", 1)
				.save();
			//根据响应结果给页面响应
			Map<String, String> result = PaymentKit.xmlToMap(xmlResult);
			String return_code = result.get("return_code");
			String return_msg = result.get("return_msg");
			if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
				renderResult(3,return_msg);
				return;
			}
			String result_code = result.get("result_code");
			String result_msg = result.get("err_code_des");
			if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
				renderResult(4,result_msg);
				return;
			}
			// 以下字段在return_code 和result_code都为SUCCESS的时候有返回
			String prepay_id = result.get("prepay_id");
			//更新订单支付方式为微信
			for(int i = 0; i < orderList.size(); i++){
				Order record = orderList.get(i);
				record.set("payMethod", OrderCode.OrderPayMethod.WEIXIN).update();
			}
			//将结果响应给页面以进行下一步操作
			Map<String, String> packageParams = new HashMap<String, String>();
			packageParams.put("appId", PropKit.get("wx.pay.appId"));
			packageParams.put("timeStamp", System.currentTimeMillis() / 1000 + "");
			packageParams.put("nonceStr", System.currentTimeMillis() + "");
			packageParams.put("package", "prepay_id=" + prepay_id);
			packageParams.put("signType", "MD5");
			packageParams.put("paySign", PaymentKit.createSign(packageParams, PropKit.get("wx.pay.key")));
			//将页面调用微信所需要的参数返回给页面
			renderSuccess(packageParams);
			return;
		}
		renderFailed("支付错误");
		return;
	}
	
	/**
	 * 交易完成
	 */
	public void tradeComplete(){
		String orderNum = getPara(0);
		if(StrKit.isBlank(orderNum)){
			redirect("/index");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null&&order.getInt("orderState")==OrderCode.OrderState.FINISH){
				setAttr("orderNum", orderNum);
				render("complete.jsp");
				return;
			}else{
				redirect("/index");
	    		return;
			}
		}
	}
	
	/**
	 * 订单列表
	 * @param state 订单类型，1：全部，2：待付款，3：待收货，4：待评价
	 */
	public void list(){
		int state = getParaToInt("state",1);
		setAttr("state", state);
		render("list.jsp");
	}
	
	/**
	 * 查询订单列表
	 * @param state 订单状态，1：全部，2：待付款，3：待收货，4：待评价
	 * @param pageNum 页码
	 * @param pageSize 数量
	 */
	public void page(){
		int pageNum = getParaToInt("pageNum",1);
		int pageSize = getParaToInt("pageSize",PropKit.getInt("constants.pageSize"));
		int state = getParaToInt("state",1);
		Page<Order> page = service.findByPage(getCurrentStoreid(),getCurrentUserid(),state,pageNum,pageSize);
		List<Order> orderList = page.getList();
		for(Order order : orderList){
			//判断订单是否允许催单，方便页面上判断是否要显示“催单”按钮
			if(urgeAble(order)==0){
				order.put("urgeAble", true);
			}
		}
		//查询订单的商品列表供页面展示
		service.getOrderGoodsList(orderList);
		renderSuccess(page);
		return;
	}
	
	/**
	 * 退款列表
	 */
	public void refund() {
		render("refund.jsp");
	}
	
	/**
	 * 查询退款订单列表
	 */
	public void pageRefund() {
		int pageNum = getParaToInt("pageNum",1);
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		Page<Order> page = service.findRefundByPage(getCurrentStoreid(), getCurrentUserid(), pageNum, pageSize);
		List<Order> orderRefundList = page.getList();
		//查询订单的商品列表供页面展示
		service.getOrderGoodsList(orderRefundList);
		renderSuccess(page);
		return;
	}
	
	/**
	 * 取消订单
	 * @param ORDERNUM 订单号
	 * @param REASON 取消订单理由
	 */
	@Before(Tx.class)
	public void cancel(){
		String orderNum = getPara("orderNum");
		String reason = getPara("reason");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“正常”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("此订单当前不允许取消");
					return;
				}
				//2.根据订单不同状态进行不同操作
				int payType = order.getInt("payType");
				int payState = order.getInt("payState");
				int packState = order.getInt("packState");
				int takeType = order.getInt("takeType");
				int deliverState = order.getInt("deliverState");
				//2.1.在线支付+送货上门，打包状态为“未接单”时可取消订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(packState!=OrderCode.OrderPackState.NO_ACCEPT){
						renderFailed("此订单当前不允许取消");
			    		return;
					}
				}else
				//2.2.在线支付+门店自取，打包状态为“未接单”时可取消订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					if(packState!=OrderCode.OrderPackState.NO_ACCEPT){
						renderFailed("此订单当前不允许取消");
			    		return;
					}
				}else
				//2.3.货到付款+送货上门时，发货状态为“未发货”时可取消订单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
						renderFailed("此订单当前不允许取消");
			    		return;
					}
				}else
				//2.4.货到付款+门店自取时，无限制
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					
				}
				try {
					//在service中进行取消订单(修改订单状态、生成退款订单)的一系列操作,保证事务回滚
					order = service.cancelOrder(order,reason,payType,payState,orderNum);
					renderSuccess(order);
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
				//5.其他情况
				renderFailed("取消订单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 删除订单
	 * @param ORDERNUM 订单号
	 */
	public void delete(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“取消”、“过期”、“完成”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.CANCEL&&orderState!=OrderCode.OrderState.EXPIRE&&orderState!=OrderCode.OrderState.FINISH){
					renderFailed("此订单当前不允许删除");
		    		return;
				}
				//2.删除订单操作，并记录日志
				order.set("orderState", OrderCode.OrderState.DELETE);
				if(order.update()){
					service.log(order.getStr("orderNum"),OrderCode.OrderLogType.DELETE,"用户",OrderCode.OrderLogType.DELETE_ACTION,"订单已删除");
					renderSuccess();
					return;
				}
				//3.其他情况
				renderFailed("删除订单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 签收
	 * @param ORDERNUM 订单号
	 */
	@Before(RefreshLoginInterceptor.class)
	public void receive(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“正常”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("此订单当前不允许签收");
		    		return;
				}
				//2.根据订单不同状态进行不同操作
				int payType = order.getInt("payType");
				int payState = order.getInt("payState");
				int takeType = order.getInt("takeType");
				int deliverState = order.getInt("deliverState");
				//2.1.在线支付+送货上门，支付状态为“已付款”，发货状态为“已发货”时可签收订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(payState!=OrderCode.OrderPayState.HAD_PAY&&deliverState!=OrderCode.OrderDeliverState.HAD_DELIVER){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
				}else
				//2.2.在线支付+门店自取，支付状态为“已付款”时可签收订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					if(payState!=OrderCode.OrderPayState.HAD_PAY){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
				}else
				//2.3.货到付款+送货上门时，发货状态为“已发货”时可签收订单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(deliverState!=OrderCode.OrderDeliverState.HAD_DELIVER){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
				}else
				//2.4.货到付款+门店自取时，无限制
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					
				}
				//3.签收订单操作，并记录日志
				try {
					//在service中进行订单签收(修改订单状态、商品返利、用户是否升级为黄金会员)的一系列操作,保证事务回滚
					service.receiveOrder(order,getCurrentUser());
					renderSuccess();
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
				//4.其他情况
				renderFailed("签收订单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 用户催单
	 * @param ORDERNUM 订单号
	 */
	public void urge(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				int urgeAble = urgeAble(order);
				if(urgeAble==1){
					renderFailed("此订单当前不允许催单");
					return;
				}else if(urgeAble==2){
					renderFailed("您的订单正在加急处理中，请耐心等待");
					return;
				}else if(urgeAble==3){
					renderFailed("您的订单正在加急处理中，请耐心等待");
					return;
				}
				try {
					//催单，修改催单累计次数加1，更新最后一次催单记录时间
					order = service.urgeOrder(getCurrentUserid(),orderNum);
					int urgeTimes = order.getInt("urgeTimes");
					String urgeLastTime = DatetimeKit.getFormatDate(order.getDate("urgeLastTime"),"yyyy-MM-dd HH:mm:ss");
					//记录日志
					service.log(orderNum,OrderCode.OrderLogType.URGE,"用户",OrderCode.OrderLogType.URGE_ACTION,"第"+order.getInt("urgeTimes")+"次催单，催单时间："+urgeLastTime+"，成功！");
					//返回客户端
					renderSuccess(MapKit.one().put("order",order).put("times", urgeTimes).put("datetime", urgeLastTime));
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
				//4.其他情况
				renderFailed("催单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 验证订单是否允许催单
	 * @param order
	 * @return 0：允许催单，1：状态不对，不允许催单，2：新下的订单只有xx分钟后才可催单，3：与上次催单时间中间隔不足xx分钟
	 */
	private int urgeAble(Order order){
		//1.判断订单状态是否为“正常”状态
		int orderState = order.getInt("orderState");
		if(orderState!=OrderCode.OrderState.NORMAL){
			//renderFailed("此订单当前不允许催单");
    		return 1;
		}
		//2.根据订单不同状态进行不同操作
		int payType = order.getInt("payType");
		int payState = order.getInt("payState");
		int takeType = order.getInt("takeType");
		int deliverState = order.getInt("deliverState");
		//2.1.在线支付+送货上门，支付状态为“已付款”，发货状态为“未发货”时可催单
		if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.DELIVER){
			if(payState!=OrderCode.OrderPayState.HAD_PAY&&deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
				//renderFailed("此订单当前不允许催单");
	    		return 1;
			}
		}else
		//2.2.在线支付+门店自取，不允许催单
		if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
			//renderFailed("此订单当前不允许催单");
    		return 1;
		}else
		//2.3.货到付款+送货上门时，发货状态为“未发货”时可催单订单
		if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.DELIVER){
			if(deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
				//renderFailed("此订单当前不允许催单");
	    		return 1;
			}
		}else
		//2.4.货到付款+门店自取时，不允许催单
		if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
    		return 1;
		}
		//3.催单操作
		int urgeTimes = order.getInt("urgeTimes");
		if(urgeTimes==0){
			//首次催单需要在下单xx分钟后
			Date orderDate = order.getDate("createDate");
			Date now = new Date();
			int diffMin = (int)(now.getTime()-orderDate.getTime())/(1000*60);
			if(diffMin<=PropKit.getInt("constants.order.urgeFirstTime")){
	    		return 2;
			}
		}else{
			//第二次以后催单，间隔需要大于xx分钟
			Date urgeLastTimeDate = order.getDate("urgeLastTime");
			Date now = new Date();
			int diffMin = (int)(now.getTime()-urgeLastTimeDate.getTime())/(1000*60);
			if(diffMin<=PropKit.getInt("constants.order.urgePerTime")){
	    		return 3;
			}
		}
		return 0;
	}
	
	/**
	 * 跳转订单详情页面
	 * @param orderNum 订单号
	 */
	public void detail(){
		setAttr("orderNum", getPara(0));
		setAttr("currentStore", getCurrentStore());
		render("detail.jsp");
	}
	
	/**
	 * 查询订单详情，及订单商品列表<br/>
	 * 注意，查询订单时，只查询订单状态“正常”、“已完成”、“已取消”的
	 * @param orderNum 订单号
	 */
	public void getDetail(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				//判断订单是否允许催单，方便页面上判断是否要显示“催单”按钮
				if(urgeAble(order)==0){
					order.put("urgeAble", true);
				}
				//查询订单的商品清单列表
				order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
				//判断如果当前订单支付方式为在线支付，且未支付时，从下单时间计算出目前还有多久过期
				if(order.getInt("orderState")==OrderCode.OrderState.NORMAL&&order.getInt("payType")==OrderCode.OrderPayType.ON_LINE&&order.getInt("payState")==OrderCode.OrderPayState.NO_PAY){
					long startTimestamp = order.getTimestamp("startDate").getTime();
					long nowTimestamp = System.currentTimeMillis();
					//判断从下单到当前的时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果小于订单过期时间，则将该数字回传给客户端
					if(nowTimestamp-startTimestamp+5*1000<PropKit.getLong("constants.order.interval")){
						//计算出离过期还剩余的毫秒数返回给客户端
						order.put("remain",PropKit.getLong("constants.order.interval")-(nowTimestamp-startTimestamp));
					}else{
						//相反，则认为订单已过期，修改订单状态返回给客户端
						order.set("orderState", OrderCode.OrderState.EXPIRE);
					}
				}
				renderSuccess(order);
				return;
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
	
	/**
	 * 跳转订单跟踪页面
	 * @param orderNum 订单号
	 */
	public void track(){
		setAttr("orderNum", getPara(0));
		render("track.jsp");
	}
	
	/**
	 * 查询订单操作日志列表<br/>
	 * @param ORDERNUM 订单号
	 */
	public void getTrack(){
		String orderNum = getPara("orderNum");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				order.put("logList", service.getLogListByOrderNum(orderNum));
				//查询订单的操作日志列表
				renderSuccess(order);
				return;
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
	
	/**
	 * 去评价
	 */
	public void eval(){
		String orderNum = getPara(0);
		if(StrKit.isBlank(orderNum)){
			redirect("/index");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				setAttr("order", order);
				render("eval.jsp");
				return;
			}else{
				redirect("/index");
				return;
			}
		}
	}
	
	/**
	 * 对订单进行评价
	 * @param ORDERNUM 订单号
	 * @param EVAL1 商品满意度
	 * @param EVAL2 配送速度满意度
	 * @param EVAL3 服务质量满意度
	 * @param CONTENT 评价内容
	 */
	public void doEval(){
		String orderNum = getPara("orderNum");
		int eval1 = getParaToInt("eval1",1);
		int eval2 = getParaToInt("eval2",1);
		int eval3 = getParaToInt("eval3",1);
		String content = getPara("content");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(content)){
			renderFailed("您还未对本次购物进行评价！");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUserid(),orderNum);
			if(order!=null){
				if(order.getInt("evalState")==0){
					if(service.doEval(orderNum, getCurrentUserid(), eval1, eval2, eval3, content)){
						//更新订单评价状态为1：已评价
						order.set("evalState", 1).update();
						//查询订单的商品清单列表
						order.put("goodsList", service.getGoodsListByOrderNum(orderNum));
						renderSuccess(order);
						return;
					}
					renderFailed("评价失败");
					return;
				}else{
					renderFailed("您已对本次购物评价过了！");
					return;
				}
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
}
